package web;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.junit.runner.Request;
import pojo.User;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.WebUtils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.tools.JavaCompiler;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author lq
 * @create 2021/1/9
 */

public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    /**
     * 注册用户
     * @param request  user
     * @param response 返回1表示成功；0表示account不可用（已存在），-1表示注册错误
     */
    protected void regist(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("in regist...");
        String account = request.getParameter("account");
        Map<String, Integer> map = new HashMap<>(16);
        if (userService.existUserName(account)) {
            map.put("status", 0);
        } else {
            User user = WebUtils.copyParamToBean(request.getParameterMap(), new User());

            System.out.println(user);
            if (userService.registUser(user)) {
                map.put("status", 1);
            } else {
                map.put("status", -1);
            }
        }
        Gson gson = new Gson();
        String userJson = gson.toJson(map);
        response.getWriter().write(userJson);
    }

    /**
     * 登录用户
     * @param request  user
     * @param response 返回1表示登录成功，返回0表示密码或账户错误
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println("in login..");
        User user = WebUtils.copyParamToBean(request.getParameterMap(), new User());
        Map<String, Integer> map = new HashMap<>(16);
        Integer id = userService.login(user.getAccount(), user.getPassword());
        if (id != null) {
            map.put("status", 1);
            map.put("ownerId",id);
        } else {
            map.put("status", 0);
        }
        Gson gson = new Gson();
        String userJson = gson.toJson(map);
        response.getWriter().write(userJson);
    }

    /**
     *获取邮箱验证码
     * @param request
     * @param response
     */
    protected void email(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
        String email = request.getParameter("email");
        int randNum = (int) (Math.random() * 100000);
        sendEmail(email, randNum);
        Map<String, Integer> map = new HashMap<>();
        map.put("num", randNum);
        Gson gson = new Gson();
        String json = gson.toJson(map);
        response.getWriter().write(json);

    }

    /**
     * 发送验证码邮箱
     * @param receiver
     * @param randNum
     */
    public void sendEmail(String receiver, int randNum) throws MessagingException {
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp");
        //发送邮件协议
        properties.setProperty("mail.smtp.auth", "true");
        //需要验证
        Session session = Session.getInstance(properties);
        session.setDebug(true);
        //邮件信息
        Message messgae = new MimeMessage(session);
        messgae.setFrom(new InternetAddress("1765116032@qq.com"));
        //设置发送人
        messgae.setText("欢迎使用四川师范大学·计算机科学学院2019JAVA实训项目【企业进销存系统】。您的验证码为：" + randNum + "。请注意，验证码有效时间为5分钟！！！");
        //设置邮件内容
        messgae.setSubject("邮箱验证");
        //设置邮件主题
        //发送邮件
        Transport tran = session.getTransport();
        tran.connect("smtp.qq.com", 587, "1765116032", "jrizfrasydjhbdjj");
        //连接到QQ邮箱服务器（端口587）
        tran.sendMessage(messgae, new Address[]{new InternetAddress(receiver)});
        //设置邮件接收人
        System.out.println("邮件发送成功");
        tran.close();
    }

    /**
     * 根据用户account，返回用户的所有信息（除了密码和头像）
     * @param request account
     * @param response user 及 status:1表示成功获取对象，0表示失败
     */
    public void getInfo(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
        String account = request.getParameter("account");
        User user= userService.findUserByUserName(account);
        Gson gson = new Gson();
        String userJson = null;
        if(user!=null){
            userJson = "{\"status\":1,\"info\":" + gson.toJson(user)+"}";
        }else{
            userJson = "{\"status\":0}";
        }
        response.getWriter().write(userJson);
        //System.out.println(userJson);
    }

    /**
     * 根据用户account，更新用户的所有信息（除了头像和密码）
     * @param request account
     * @param response 1表示更新正确，0表示错误
     */
    public void updateInfo(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
        String account = request.getParameter("account");
        Map<String,Integer> map = new HashMap<>();
        if(userService.updateUser(userService.findUserByUserName(account))){
            map.put("status", 1);
        }else{
            map.put("status", 0);
        }
        Gson gson = new Gson();
        String userJson = gson.toJson(map);
        response.getWriter().print(userJson);
    }

    /**
     * 根据用户email，更新用户的密码
     * @param request
     * @param response
     */
    public void updatePsd(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
        String email = request.getParameter("email");
        String password  = request.getParameter("password");
        Map<String,Integer> map = new HashMap<>();
        if(userService.updatePwd(email,password)){
            map.put("status", 1);
        }else{
            map.put("status", 0);
        }
        Gson gson = new Gson();
        String userJson = gson.toJson(map);
        response.getWriter().print(userJson);
    }

    /**
     * 根据用户id，获取用户的头像
     * @param request
     * @param response
     */
    // TODO： 暂时不做头像
    public void getImg(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {

    }

    /**
     * 根据用户id，更新用户的头像
     * @param request
     * @param response
     */
    // TODO： 暂时不做头像
    public void updateImg(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {

    }


//    /**
//     * 根据用户account删除用户
//     * @param request account
//     * @param response 1表示删除正确，0表示错误
//     */
//    public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
//        String account = request.getParameter("account");
//        Map<String,Integer> map = new HashMap<>();
//        if(userService.deleteUser(account)){
//            map.put("status", 1);
//        }else{
//            map.put("status", 0);
//        }
//        Gson gson = new Gson();
//        String userJson = gson.toJson(map);
//        response.getWriter().print(userJson);
//    }

//    /**
//     * 保存用户信息
//     * @param request user
//     * @param response 1表示保存正确，0表示错误
//     */
//    public void saveUser(HttpServletRequest request, HttpServletResponse response) throws MessagingException, IOException {
//        User user = WebUtils.copyParamToBean(request.getParameterMap(), new User());
//        Map<String,Integer> map = new HashMap<>();
//        if(userService.saveUser(user)){
//            map.put("status", 1);
//        }else{
//            map.put("status", 0);
//        }
//        Gson gson = new Gson();
//        String userJson = gson.toJson(map);
//        response.getWriter().print(userJson);
//    }
}
